<template>
  <div v-if="selectPlatform == 2">
    <div class="gva-table-box">
      <div style="font-size: 200%;margin-bottom: 10px">
        AB测计划
      </div>
      <div class="gva-btn-list">
        <el-button
          type="primary"
          icon="plus"
          @click="openDialog"
        >新增</el-button>
      </div>
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        border
        row-key="id"
      >
        <el-table-column
          align="left"
          label="计划自定义标识"
          prop="flag"
        />
        <el-table-column
          align="left"
          label="计划状态"
        >
          <template #default="scope">
            {{ scope.row.status === 1 ? '关闭' : '进行中' }}
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="数据"
        >
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="search"
              class="table-button"
              @click="showData(scope.row)"
            >数据</el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="操作"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="edit"
              class="table-button"
              @click="update(scope.row)"
            >编辑</el-button>
            <el-button
              type="primary"
              link
              icon="edit"
              class="table-button"
              @click="detail(scope.row)"
            >详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div> -->
    </div>
    <el-dialog
      v-model="dialogFormVisible"
      :before-close="closeDialog"
      :title="type==='create'?'添加':'修改'"
      destroy-on-close
    >
      <el-scrollbar height="400px">
        <el-form
          ref="elFormRef"
          :model="formData"
          label-position="right"
          :rules="rule"
          label-width="100px"
        >
          <el-form-item
            label="计划标识:"
            prop="flag"
          >
            <el-input
              v-model="formData.flag"
              :clearable="true"
              placeholder="请输入计划标识"
            />
          </el-form-item>
          <el-form-item
            label="状态:"
            prop="status"
          >
            <el-select v-model.number="formData.status">
              <el-option
                label="关闭"
                :value="1"
              />
              <el-option
                label="进行中"
                :value="2"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="enterDialog"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  createAbTest,
  updateAbTest,
  findAbTest,
  getAbTestList
} from '@/api/qmAbTest'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'

defineOptions({
  name: 'AbTest'
})

const route = useRoute()
const router = useRouter()

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  projectId: Number(route.query.id),
  flag: '',
  status: undefined
})

// 验证规则
const rule = reactive({
  flag: [
    { required: true, message: '请输入计划标识', trigger: 'blur' }
  ],
  status: [{
    required: true,
    message: '请选择状态',
    trigger: ['input', 'blur'],
  },
  ],
})

const selectPlatform = ref(1)
const isPlatform = () => {
  const platform = localStorage.getItem('platform')
  if (platform == 0 || platform == '' || platform == null || platform == undefined) {
    ElMessage({
      type: 'error',
      message: '请先选择渠道'
    })
    selectPlatform.value = 1
    // setTimeout(() => {
    //   window.location.href = '/#/layout/dashboard'
    // }, 1000)
  } else {
    selectPlatform.value = 2
  }
}

isPlatform()

const elFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])

// 查询
const getTableData = async() => {
  const table = await getAbTestList({ projectId: route.query.id })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============
const platformOptions = ref([])
// 获取需要的字典 可能为空 按需保留
const setOptions = async() => {
  platformOptions.value = await getDictFunc('platform')
}

// 获取需要的字典 可能为空 按需保留
setOptions()

const showData = (row) => {
  router.push({
    name: 'qmAbTestData',
    query: {
      id: row.id
    }
  })
}

const detail = (row) => {
  router.push({
    name: 'abTestDetail',
    query: {
      id: row.id
    }
  })
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

const update = async(row) => {
  const res = await findAbTest({ id: row.id })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data
    dialogFormVisible.value = true
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    status: undefined,
    projectId: Number(route.query.id),
    flag: ''
  }
}
// 弹窗确定
const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return
    let res
    switch (type.value) {
      case 'create':
        res = await createAbTest(formData.value)
        break
      case 'update':
        res = await updateAbTest(formData.value)
        break
      default:
        res = await createAbTest(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

</script>

<style>

</style>
